package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.mq.listener.vo.IotMsgNotifyData;
import com.zzyl.nursing.mq.listener.vo.IotMsgService;
import com.zzyl.nursing.service.IDeviceDataService;
import com.zzyl.nursing.service.IDeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 设备数据Service业务层处理
 *
 * @author alexis
 * @date 2025-06-06
 */
@Service
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService {
    @Autowired
    private DeviceDataMapper deviceDataMapper;

    @Autowired
    private IDeviceService deviceService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 查询设备数据
     *
     * @param id 设备数据主键
     * @return 设备数据
     */
    @Override
    public DeviceData selectDeviceDataById(Long id) {
        return deviceDataMapper.selectById(id);
    }

    /**
     * 查询设备数据列表
     *
     * @param deviceData 设备数据
     * @return 设备数据
     */
    @Override
    public List<DeviceData> selectDeviceDataList(DeviceData deviceData) {
        return deviceDataMapper.selectDeviceDataList(deviceData);
    }

    /**
     * 新增设备数据
     *
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData) {
        return deviceDataMapper.insert(deviceData);
    }

    /**
     * 修改设备数据
     *
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData) {
        return deviceDataMapper.updateById(deviceData);
    }

    /**
     * 批量删除设备数据
     *
     * @param ids 需要删除的设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids) {
        return deviceDataMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 批量保存数据
     *
     * @param iotMsgNotifyData iot消息
     */
    @Override
    @Transactional
    public void batchInsertDeviceData(IotMsgNotifyData iotMsgNotifyData) {
        // 1.通过id查询设备
        String iotId = iotMsgNotifyData.getHeader().getDeviceId();
        Device device = deviceService.lambdaQuery().eq(Device::getIotId, iotId).one();

        // 2.判断设备是否存在
        if (ObjectUtil.isEmpty(device)) {
            throw new BaseException("设备不存在");
        }

        // 3.构建设备数据
        List<DeviceData> deviceDataList = new ArrayList<>();

        // 4.用双重循环解析数据，并添加到集合中
        List<IotMsgService> iotMsgServiceList = iotMsgNotifyData.getBody().getServices();
        if (CollectionUtil.isEmpty(iotMsgServiceList)) {
            log.warn("设备数据为空");
            return;
        }

        iotMsgServiceList.forEach(service -> {
            Map<String, Object> properties = service.getProperties();
            if (ObjectUtil.isEmpty(properties)) {
                return;
            }

            // 处理数据上报时间
            LocalDateTime alarmTime = DateUtils.convertActiveTime(service.getEventTime(), "yyyyMMdd'T'HHmmss'Z'");

            properties.forEach((k, v) -> {
                DeviceData deviceData = BeanUtil.toBean(device, DeviceData.class);
                // 让主键自增
                deviceData.setId(null);
                deviceData.setFunctionId(k);
                deviceData.setAccessLocation(device.getRemark());
                deviceData.setDataValue(v.toString());
                deviceData.setAlarmTime(alarmTime);

                deviceDataList.add(deviceData);
            });

        });

        // 5.批量保存数据
        saveBatch(deviceDataList);

        // 6.将最新数据存储到redis中
        redisTemplate.opsForHash().put(CacheConstants.IOT_DEVICE_LAST_DATA, iotId, JSONUtil.toJsonStr(deviceDataList));
    }

    /**
     * 定时清理设备数据
     */
    @Override
    public void clearDeviceData() {
        // 获取15天前的日期
        LocalDateTime fifteenDaysAgo = LocalDateTime.now().minusDays(15);
        // 删除过期数据
        lambdaUpdate().lt(DeviceData::getAlarmTime, fifteenDaysAgo).remove();
    }
}
